import teamName from "components/teamName";
import U_regionExternalReward from "components/new_diy/incomeWithdrawal.vue";
// import QRCode from 'qrcode';
import emptyImage from "@/assets/images/new_diy/image.png";
import yzGoodsposter from "components/ui_components/yz_goodsPoster";
import DConnectCustomerService from "@/components/other/common/DConnectCustomerService";
import base64_encode from "../../utils/base64_encode";
// 云店会员中心模块
import cloud_shop_member from "../cloud_shop/components/cloud_shop_member";
// 实习店长未完成任务每次都弹出 弹窗指引的弹窗
import guidancePopup from "../cloud_shop/components/guidancePopup";
// 云店 模版3 
import cloud_shop_template from "../cloud_shop/components/cloud_shop_template";

window.memberAdvertisement = 1; //弹出周期设置为关闭网页(弹窗广告)
const documentElement = document.documentElement;
const body = document.body;

export default {
  data() {
    return {
      loading: true,
      is_login: 0,
      isLoadMore: true,
      components: [],
      background_color: "#ffc11e", //背景主题色
      swiperOption: {
        autoplay: false,
        // loop: true,   loop模式第二轮循环的时候第一张会闪烁
        delay: 3000,
        observer: true,
        pagination: {
          el: ".swiper-pagination"
        }
      },
      isBottom: false,
      btnFlag: false,
      btnData: {
        button_size: 40,
        over_top: 550,
        position_location: "right",
        icon_url: ""
      },

      popShow: false, //弹窗广告显示
      showPopup: false,//客服弹窗
      buttonClientWidth: "",
      teamNameShow: false, //团队名称显示

      // 海报
      posterShow: false,
      poster: "",
      poster_Data: {
        poster_data: null,
        background: {}
      },
      poster_id: null, //海报id

      templateValue: '', //模板样式 (目前有三种，模板1、模板2、装修diy页面) 云店模式新增模版3
      member_info: {}, //顶部会员信息
      order: [], //订单列表信息
      plugin_data: [], //底部选项卡
      plugins: [], //插件入口汇总
      assets: [], //资产数据
      foot: {}, //底部版权模块

      // 底部装修选项卡 配置
      recommendGoods: recommendGoods,
      fightGroups: {},
      ywmFightGroups: {},
      limitBuyGoods: limitBuyGoods,
      article: article,
      storeCashier: storeCashier,
      microCommunities: microCommunities,
      videoShare: videoShare,
      room: room,
      plugin_active: null,
      // 底部装修选项卡  end

      point: {},
      other: {
        setting: {
          wechat_login_mode: false,//是否是微信授权登录，用于处理是否显示退出登录按钮
        }
      },
      default_head_img:"https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/photo-mr.jpg",
      show_login_button:false,
      is_shop_owner:0,
      guide_show_status:0,
      shop_level_name:''
    };
  },
  activated() {
    this.getMemberData();
    window.addEventListener("scroll", this.handleScroll);
    let  basic_info =  JSON.parse(localStorage.getItem('yz_basic_info'));
    if(basic_info?.home?.mailInfo?.default_head_img){
      this.default_head_img = basic_info?.home?.mailInfo?.default_head_img
    }
  },
  deactivated() {
    window.removeEventListener("scroll", this.handleScroll);
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.$nextTick(() => {
      let myAudio =  document.getElementById('myAudio')
      if (this.fun.isWeiXin() && this.fun.isIosOrAndroid() === "ios" && myAudio) {
        document.addEventListener(
          "WeixinJSBridgeReady",
          function() {
            myAudio.pause();
            document.body.removeChild(myAudio);
          },
          false
        );
      }
      if(myAudio) {
        myAudio.pause();
        document.body.removeChild(myAudio);
      }
    })
  },
  computed: {
    assetsAudio() {
      if(this.assets && this.assets.length > 0) {
        let audioFlag =  this.assets.some((item) => item.is_change == 1);
        if(audioFlag) {
            this.$nextTick(() => {
              this.createVoiceDom(this.other?.mark_sound?.sound_link);
            })
        }
      }
    }
  },
  watch:{

  },
  created() {},
  mounted() {
    this.buttonClientWidth = document.body.clientWidth - 56 + "px";
    if (this.fun.isWeiXin() && this.fun.isIosOrAndroid() === "ios") {
      let myAudio =  document.getElementById('myAudio');
      if(myAudio) {
        document.addEventListener(
          "WeixinJSBridgeReady",
          function() {
            myAudio.play();
          },
          false
        );
      }
    }
  },
  methods: {
    update_guide_Methods(){
      // 子组件请求接口成功后修改状态
      this.other.cloud_shop.guide_status = 2;
    },
    //爱心值音频播放功能
    createVoiceDom(_url) {
      //创建音频dom
      // let that = this;
      let link = document.createElement("audio");
      link.setAttribute("src", _url);
      link.setAttribute("autoplay", true);
      link.setAttribute("id", 'myAudio');
      document.body.appendChild(link);
      //this.fun.isWeiXin() &&
      if (this.fun.isWeiXin() && this.fun.isIosOrAndroid() === "ios") {
        this.$nextTick(() => {
          document.addEventListener(
            "WeixinJSBridgeReady",
            function() {
              link.play();
            },
            false
          );
        })
      } else {
        link.play();
      }
    },
    //处理爱心值装修数据
    setAssetData(datas,other) {
      if(datas && datas.length > 0){
        let memberasset = datas.filter((item) => item.component_key == 'U_memberasset');
        let showList = memberasset[0]?.remote_data?.show_list;
        let audioFlag = false;
        if(showList && showList.length > 0) {
          audioFlag = showList.some((item) => item.is_change == 1);
        }
        if(audioFlag) {
          this.$nextTick(() => {
            this.createVoiceDom(other?.mark_sound?.sound_link);
          })
        }
      }
    },
    toEditAvatar(){
      this.$router.push(this.fun.getUrl('userinfo', {}, {
        pageType: 'UserInformation'
      }));
    },
    // 跳转页面
    goToUrl(name, params = {}, query = {}) {
      if (!name) return;
      this.$router.push(this.fun.getUrl(name, params, query));
    },
    toOrderList(order_key, item) {

      // 考虑优化重构
      if (item.status_name.indexOf("售后") > -1 && order_key != "coupon-store") {
        this.$router.push(this.fun.getUrl("aftersaleslist"));
        return;
      }
      let status = Number(item.status) + 1;
      let orderType = order_key;
      let pageUrl = 'orderlist';
      switch (order_key) {
      case 'shop':
      case 'order':
        break;
      case 'hotel':
        status = item.status === 11 ? 5 : Number(item.status) + 1;
        pageUrl = 'hotelOrderlist';
        break;
      case 'fight-groups':
      case 'fight_groups_order':
        status = Number(item.status) + 2;
        orderType = "groups";
        pageUrl = 'GroupOrderlist';
        break;
      case 'snatch-regiment':
        orderType = "grabGroup";
        break;
      case 'lease-toy':
        orderType = "lease_toy";
        pageUrl = 'lease_toyOrderlist';
        break;
      case 'live-install-work':
        status = item.status === -1 ? 1 : item.status;
        pageUrl = 'installationSeverHome';
        return this.$router.push(this.fun.getUrl("installationSeverHome", {}, { status: Number(status) }));
        break;
      case 'live-install':
        status = Number(item.status) + 1;
        pageUrl = 'installationSeverMemberHome';
        return this.$router.push(this.fun.getUrl("installationSeverMemberHome", {}, { status: status }));
        break;
      case 'aggregation-cps':
        if (item.status === -3) {
          pageUrl = 'cpsCouponList';
        } else {
          pageUrl = 'cpsOrderList';
        }
        status = item.status === 3 ? null : item.status;
        return this.$router.push(this.fun.getUrl(pageUrl, {}, { status: status }));
        break;
      case 'group-work':
        orderType = "groupWork";
        break;
      case 'ywm-fight-groups':
        status = item.status;
        orderType = "ywmgroups";
        break;
      case 'coupon-store':
        pageUrl = 'ticketOrderList';
        status = item.status;
        return this.$router.push(this.fun.getUrl("ticketOrderList", {}, { status: item.status }));
        break;
      case "travel-around":
        orderType = "travelAround";
        break;
      case "yz-supply-cake":
        orderType = "sachertorte";
        break;
      case "union-cps":
        pageUrl = 'unionCpsOrder';
        status = item.status;
        if(Number(item.status) == -2) status = 4;
        break;
      case "tiktokcps":
        return  this.$router.push(this.fun.getUrl("TikTokOrder", {}, { status: item.status}));
        break;
      case "meituan-group-buy":
        return this.$router.push(this.fun.getUrl("MeiTuanOrder", {}, { status: item.status}));
      case "yz-supply-lease":
        pageUrl = 'yz_lease_toyOrderlist';
        orderType = "yz_lease_toy";
        break;
      case "collection-center":
        orderType = "collectionCenter";
        if(Number(item.status) == 3 ) status = 2;
        break;
      case "tiktok-group-buy":
          console.log("清清浅浅")
        return   this.$router.push(this.fun.getUrl("DyOrder", {}, { status: item.status}));
      case "storeOilStation":
        // 油站订单列表
        pageUrl = `oilOrder`;
        orderType = "storeOilStation"
        if (status == 1){
          status = 1;
        } else if (status == 2){
          status = 2;
        }else {
          status = 0;
        }
        break
      case "store-projects":
        status -= 1;
        if( status == 3 ){
          status = 2;
        } else if( status == -2 ){
          status = 3;
        }
        break
      default:
        console.error("Invalid order key:", order_key);
        // return;
        break;
      }
      if(Number(item.status) == -2 && status < 0) status = 0;
      this.$router.push(this.fun.getUrl(pageUrl, { status: status.toString(), orderType: orderType }));
    },
    isInWechatMp(){
      if(navigator.userAgent.match(/miniprogram/i) || window._wxjs_environment === 'miniprogram'){
        return true;
      }
      return false;
    },
    checkShowButton(){
      if(this.is_login){
        if( this.fun.getTyep() == 5 && this.isInWechatMp() && !this.other?.setting.wechat_login_mode){
          // type == 5 并且是微信小程序web-view打开,并且 开启了微信授权按钮,都不显示退出按钮
          return false
        }
        if( ((this.fun.getTyep() != 1 && this.fun.getTyep() != 2) || (this.other.setting && this.other.setting.wechat_login_mode)) && this.show_login_button){
          // type != 1和type != 2 或者 没开启微信授权 并且 后台会员中心退出按钮开启
          return true
        }
      } else {
        return false
      }
    },
    getMemberData() {
      this.loading = true;
      let _url = 'member.member.member-data';
      if (this.$route.name == 'supplier_alone_member') {
        _url = 'plugin.supplier-alone-temp.frontend.member.index';
      }
      $http
        .post(_url, { v: 2, basic_info: 1 , page_id: this.fun.getKey("page_id")|| ''}, " ")
        .then(
          response => {
            this.loading = false;
            if (response.result === 1) {
              this.fun.setWXTitle($i18n.t("会员中心"));
              let { member_info, order = [], plugin_data = [], plugins = {}, assets = [], foot = {}, designer, other = {}, is_login } = response.data;
              this.foot = foot; //底部版权设置信息
              this.other = other;
              let integralPact = response.basic_info?.plugin_setting?.integral;
              this.is_login = is_login !== undefined ? is_login: 1;//判断是否已登录
              this.wechat_login_mode = other?.setting?.wechat_login_mode;//是否开启了微信授权，0为开启
              this.show_login_button = other?.setting?.show_login_button == "0" ? true : false;
              if (this.is_login === 0) {
                this.$dialog
                  .confirm({
                    title: `欢迎来到${response.basic_info.home?.mailInfo?.name}`,
                    message: "登录尽享各种优惠！",
                    confirmButtonText: "登录/注册",
                    cancelButtonText: "暂不登录",
                    confirmButtonColor: response.basic_info.theme_color
                  })
                  .then(() => {
                    this.toAuthorizedLogin();
                  });
              }
              if(integralPact && integralPact.needSign && this.is_login) { //消费积分签署合同
                this.$dialog.alert({
                  title: '提示',
                  message: '请先完成合同签署',
                }).then(() => {
                  return this.$router.replace(this.fun.getUrl("shopSignIndexV2",{scene: 4}));//需要先签署合同
                });
              }
              if (designer) {
                if (designer.page_info) {
                  // 会员浏览权限
                  this.$store.commit("setWatchMemberDiypage", designer.page_info.allowauth);
                  if( designer.page_info.allowauth == 0) this.loading = true;
                  if (designer.page_info.allowauth == 0 && designer.page_info.member_level_url && designer.page_info.member_level_url.link) {
                    this.timer = setTimeout(() => {
                      clearTimeout(this.timer);
                      window.location.href = designer.page_info.member_level_url.link;
                    }, 3000);
                    return;
                  }
                }
                this.getNewDecorate(designer);
                this.components = designer.datas;
                this.templateValue = "designer";
                this.setAssetData(designer.datas,other);
                return;//设置装修后，这里 return 了，不走下面逻辑 ！！！！！！！！！！！！！
              } else if (this.$store.state.temp.item.is_decorate === 1) {
                if (this.$store.state.temp.item.ViewSet.member.is_default != 0) {
                  this.templateValue = this.$store.state.temp.item.ViewSet.member.code.substring(6); //获取模板设置
                } else {
                  this.templateValue = "01";
                }
              } else {
                this.templateValue = "01";
              }
              console.log('sssssss',this.templateValue)
              if(response.basic_info?.plugin_setting?.cloud_shop?.open_state){
                // 云店模板
                this.templateValue = '03';
                this.is_shop_owner = response.basic_info?.plugin_setting?.cloud_shop?.is_shop_owner;
                this.guide_show_status = response.basic_info?.plugin_setting?.cloud_shop?.guide_show_status;
                this.shop_level_name = response.basic_info?.plugin_setting?.cloud_shop?.shop_level_name;
                if(this.other.cloud_shop){
                  let otherInfo = this.other.cloud_shop;
                  if(this.is_shop_owner && otherInfo.is_base == 1 ){
                    if(this.guide_show_status == 1){
                      // 有开启实习指引
                      if(otherInfo.guide_status != 2 || otherInfo.wechat_follow != 1 || otherInfo.first_order_status != 1){
                        // 没有看完课程
                        this.$refs.guidance.otherInfo = otherInfo;
                        this.$refs.guidance.show = true;
                      }
                    }else{
                      if(otherInfo.wechat_follow != 1 || otherInfo.first_order_status != 1){
                        // 没有开启实习指引 wechat_follow != 1 或 first_order_status != 1 没完成就弹
                        this.$refs.guidance.otherInfo = otherInfo;
                        this.$refs.guidance.show = true;
                      }
                      
                    }
                  }
                }
              }

              this.member_info = member_info;
              this.order = order;
              this.plugin_data = plugin_data;
              this.plugins = plugins;
              this.assets = assets;

              if (plugins.body) {
                // plugins.body.push({
                //   class: "icon-zb_all_more",
                //   image: "",
                //   mini_url: "",
                //   name: "morePlugin",
                //   title: "更多工具",
                //   url: "morePlugin"
                // });
                let page = Math.ceil(plugins.body.length / 10); //==> 页数
                let num = 10; // ==> 每页多少个
                let _plugin_list = [];
                for (let i = 0; i < page; i++) {
                  _plugin_list.push(plugins.body.slice(i * num, (i + 1) * num));
                }
                this.plugins.body = _plugin_list;
              }

              if (plugin_data && plugin_data.length > 0) {
                if (plugin_data.length > 0) {
                  this.plugin_active = plugin_data[0].code;
                  const activePlugin = this[this.plugin_active];
                  const pluginData = plugin_data[0]?.data;

                  activePlugin.current_page = pluginData?.current_page;
                  activePlugin.last_page = pluginData?.last_page;

                  switch (this.plugin_active) {
                  case 'microCommunities':
                  case 'storeCashier':
                  case 'limitBuyGoods':
                    activePlugin.list = pluginData || [];
                    break;
                  case 'videoShare':
                    activePlugin.list = pluginData?.list || [];
                    activePlugin.current_page = pluginData?.list?.current_page;
                    activePlugin.last_page = pluginData?.list?.last_page;
                    break;
                  case 'article':
                    activePlugin.list = pluginData?.articles || [];
                    activePlugin.current_page = pluginData?.articles?.current_page;
                    activePlugin.last_page = pluginData?.articles?.last_page;
                    break;
                  default:
                    activePlugin.list = pluginData?.data || [];
                    break;
                  }
                  this[this.plugin_active] = activePlugin;
                }
              }
            } else {
              // this.templateValue = '02';
              this.$toast(response.msg);
            }
          },
          response => {
            // this.templateValue = '02';
            console.log(response.msg);
          }
        )
        .catch(err => {
          console.error(err);
          this.$toast(err);
          // this.templateValue = '02';
          // if (this.$store.state.isWXlogined == 0) {
          //   this.$dialog
          //     .confirm({
          //       title: "欢迎来到",
          //       message: "登录尽享各种优惠！",
          //       confirmButtonText: "微信授权",
          //       cancelButtonText: "暂不登录"
          //     })
          //     .then(() => {
          //       this.toAuthorizedLogin();
          //     });
          // }
        });
    },
    pluginGoto(item) {
      if (item.diy_url) {
        window.location.href = item.diy_url;
        return;
      }
      let params = { fromHome: 1 };
      if (item.name == "article") params = { id: "0" };
      if (item.name == "supplier") params = { uid: this.supplier_id };

      if (item.name == "order-inventory") {
        return this.$router.push(this.fun.getUrl("stockorderList", { stock: "stock" }));
      }
      if (item.name == "m-erweima" && item.mini_url == 'm-erweima') {
        return this.openQrCode("block"); // 海报
      }
      if (item.name == "qq-advertise") {
        return this.gotoAppRevardVideo(item); //跳转客户app观看广告
      }
      if (item.url == "SilverBankList/wisdom") {
        return this.$router.replace(this.fun.getUrl("SilverBankList", { option: "wisdom" }));
      }
      if(item.url=='water_machine_consumer'){
        let _query = {};
        let device_no = window.localStorage.getItem('device_no');
        if(device_no){
          _query.device_no = device_no;
        }
        return this.$router.push(this.fun.getUrl(item.url, {}, _query));
      }
      let query = {};
      if(item.page_data) {
        let { data_url, ...othder } = item.page_data;
        query = { ...othder };
        if(data_url) {
          query.api = data_url;
        }
      }
      this.$router.push(this.fun.getUrl(item.url, params, query));
    },

    async handlePlugin() {
      this.setLoadMore(true);
      if(this.plugin_active == 'storeCashier'){
        this.fun.getLocation()
          .then((res)=> {
            this.point = res.point;
            this._handleBottomPluginData(this.plugin_active, "getList");
          })
          .catch((err)=> {
            console.log(err);
          });
      } else {
        this._handleBottomPluginData(this.plugin_active, "getList");
      }

    },
    getMorePluginData(){
      this._handleBottomPluginData(this.plugin_active, "getMore");
    },

    async _handleBottomPluginData(name, fn) {
      /*
        处理 模板1 底部装修组件数据加载
        getList
          // 这里处理获取首次或者第一页的请求
        ,
        getMore
          // 这里处理加载更多

        }
      */
      let _this = this;
      if(fn == 'getList') {
        let { data } = await $http.get("member.member.plugin-data", { code: name, page: 1 ,lng: this.point.lng || '0', lat: this.point.lat|| '0' }, "loading");

        _this[name].current_page = data.current_page;
        _this[name].last_page = data.last_page;
        if(name == 'microCommunities'|| name == 'storeCashier'||name == 'limitBuyGoods') {
          _this.$set(_this[name], "list", data);
        } else if(name == 'videoShare') {
          _this.$set(_this[name], "list", data.list);
          _this[name].current_page = data.list.current_page;
          _this[name].last_page = data.list.last_page;
        } else if(name == 'article') {
          _this.$set(_this[name], "list", data.articles);
          _this[name].current_page = data.articles.current_page;
          _this[name].last_page = data.articles.last_page;
        } else {
          _this.$set(_this[name], "list", data.data);
        }
      }
      if(fn == 'getMore') {
        if (_this[name].current_page < _this[name].last_page) {
          _this[name].current_page += 1;
          if(!this.$refs[name]) return;

          _this.setLoadMore(false);
          if(name == 'limitBuyGoods') {
            this.$refs.limitBuyGoods[0].loadMoreMemberData();
          } else if(name == 'fightGroups'||name == 'ywmFightGroups'){
            let { data } = await $http.get("member.member.plugin-data", { page: _this[name].current_page , code: name, lng: this.point.lng, lat: this.point.lat}, "loading");
            let _list = _this[name].list.concat(data.data);
            _this.$set(_this[name], "list", _list);
          } else if(name == 'videoShare') {
            this.$refs.videoShare[0].loadMoreMemberData();
          } else if(name == 'article') {
            this.$refs.article[0].getMoreData();
          } else if(name == 'microCommunities') {
            this.$refs.microCommunities[0].getMoreData();
          } else if(name == 'storeCashier') {
            this.$refs.storeCashier[0].getMoreList();
          } else {
            console.log('未找到对应的！！');
          }
          // _this.setLoadMore(true);
        }
      }
    },
    setLoadMore(flag) {
      this.isLoadMore = flag;
    },

    openService() {
      // 客服插件
      if (this.other.service.cservice || this.other.service.service_QRcode || this.other.service.service_mobile) {
        this.showPopup = true;
      } else {
        window.location.href = this.other.service;
      }
    },

    // 退出登录
    outInfo() {
      $http.get("member.logout.index").then(
        response => {
          if (response.result == 1) {
            window.localStorage.setItem("isWxLogin", -1);
            this.$store.commit("savemodel", {});
            localStorage.setItem("token", "");
            localStorage.setItem("loginUid", "");
            window.localStorage.removeItem('uid');
            window.firstLogin = 0;
            clearLoginData(); // 方法在index.html
            if (this.fun.isCPS() && this.fun.isCPSAPPI()) {
              // 聚合APP退出方法
              if (this.fun.isIosOrAndroid() === "ios") {
                toQuitIOS({ body: "toQuitIOS" });
              } else {
                toQuitAndroid();
              }
              return;
            }

            this.$dialog
              .alert({ message: response.msg })
              .then(() => {
                this.$router.push(this.fun.getUrl("login",{},{mid: ''}));
              })
              .catch(() => {});
          }
        },
        response => {
          console.log(response.msg);
        }
      );
    },

    // ---------团队名称插件-------
    teamCancelTap() {
      this.teamNameShow = false;
    },
    childEdit(e) {
      this.member_info.member_team.team_name = e;
    },
    TapEdit() {
      if (this.member_info.member_team.can_edit) {
        this.teamNameShow = true;
      }
    },
    // ---------团队名称插件 end-------
    copyLink() {
      if (!this.fun.isTextEmpty(this.foot.cat_adv_url)) {
        window.location.href = this.foot.cat_adv_url;
      }
    },

    // ----------- 装修diy 数据处理 ------------------
    getNewDecorate(data) {
      this.page_id = data.id;
      if (data.page) {
        this.total_page = data.page.total_page;
        this.current_page = data.page.current_page;
        this.lastIndex = data.page.count - 1;
      }

      if (data.page_info) {
        //会员中心只有弹窗广告
        this.advertising = data.page_info.advertising_id;
        if (this.advertising.id && this.advertising.datas) {
          this.advertising.datas = JSON.parse(this.advertising.datas);
        }
      }

      if (this.advertising && this.advertising.id && window.memberAdvertisement === 1 && this.advertising.show_rule === 1) {
        window.memberAdvertisement = 0;
        this.popShow = true;
        this.$nextTick(() => {
          this.initAdvertising();
        });
      }
    },
    getMoreDecorate() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.current_page < this.total_page) {
        this.current_page = this.current_page + 1;
        $http.get("plugin.decorate.frotend.decorate-api.get-page", { decorate_page: this.current_page, decorate_id: this.page_id }, "..").then(response => {
          if (response.result == 1) {
            this.isLoadMore = true;
            this.components = this.components.concat(response.data.datas);
          } else {
            this.isLoadMore = false;
            this.current_page = this.current_page - 1;
          }
        });
      } else {
        console.log("加载完了");
      }
    },
    // ----------- 装修diy 数据处理  end------------------
    //  ----------- 广告弹窗 -----------
    getImg(url, callback) {
      // 图片加载完回调
      let img = new Image();
      img.src = url;
      //如果图片被缓存，则直接返回缓存数据
      if (img.complete) {
        callback(Number(img.height) / Number(img.width));
      } else {
        //完全加载完毕的事件
        img.onload = function() {
          callback(Number(img.height) / Number(img.width));
        };
        img.onerror = function() {
          console.log("图片加载出错");
        };
      }
    },
    initAdvertising() {
      let that = this;
      this.getImg(this.advertising.image, function(scale) {
        // 图片加载完后获取图片高度
        let script = document.createElement("script");
        script.type = "text/wxtag-template";
        script.text = `<div style="width: ${that.clientWidth * 0.65}px;height: ${that.clientWidth * 0.65 * scale}px;"></div>`;
        that.advertising.html = `<wx-open-launch-weapp username="${that.advertising.s_id}" path="${that.advertising.s_url}">${script.outerHTML}</wx-open-launch-weapp>`;
        that.$forceUpdate();
      });
    },
    closePop() {
      this.popShow = false;
    },
    turnTo() {
      if (this.advertising.h_url) {
        if (this.advertising.h_url === window.location.href) {
          this.popShow = false;
        } else {
          window.location.href = this.advertising.h_url;
        }
      }
    },
    //  ----------- 广告弹窗 end-----------

    //  海报生成
    openQrCode(e) {
      this.getPoster(e);
    },
    // 云店点海报生成
    cloud_shop_Qrcode(){
      this.openQrCode("block"); // 海报
    },
    openQrCode_old(e) {
      if (!this.poster) {
        if (!this.timer) {
          this.getPoster_oldApi(e);
          this.timer = setInterval(() => {
            this.getPoster_oldApi(e);
          }, 3000);
        }
      } else {
        clearInterval(this.timer);
        this.toastPoster.clear();
      }
    },
    getPoster(e) {
      if (!this.fun.isTextEmpty(this.poster_Data.poster_data) || !this.fun.isTextEmpty(this.poster)) {
        this.posterShow = true;
        return;
      }
      let that = this;
      $http.get("member.qrcode.get-poster", {}, {}).then(
        response => {
          if (response.result === 1) {
            this.isNewPosterPlugin = response.data.new || false;
            if (response.data.center_show == 0) {
              //0 返回的默认图片
              that.poster = response.data.image_url;
              that.posterShow = true;
            } else if (response.data.center_show == 1) {
              //前端生成
              that.poster_Data.background.src = response.data.background_url || response.data.background;
              that.poster_Data.background.type = "background";
              that.poster_Data.poster_data = response.data.style_data;
              that.poster_id = response.data.id;
              that.posterShow = true;
            } else if (response.data.center_show == 2) {
              //部分关注二维码不支持跨域，走老接口
              that.toastPoster = this.$toast({
                duration: -1, // 持续展示 toast
                message: "正在为您生成海报中"
              });
              that.openQrCode_old(e);
            }
          } else {
            this.$toast(response.msg);
          }
        },
        response => {
          this.clearPostetInterval();
        }
      );
    },
    getPoster_oldApi(e) {
      $http.get("member.poster").then(
        response => {
          if (response.result === 1) {
            this.poster = response.data.image_url;
            if (this.poster) this.clearPostetInterval();
          } else {
            this.$toast(response.msg);
            this.clearPostetInterval();
          }
        },
        response => {
          this.clearPostetInterval();
        }
      );
    },
    clearPostetInterval() {
      if (this.timer) {
        this.posterShow = true;
        clearInterval(this.timer);
        if (this.toastPoster) {
          this.toastPoster.clear();
        }
      }
    },
    uploadImageM(e) {
      //图片上传
      this.dataURL = e;
      let uploadImage = this.fun.getRealUrl("member.qrcode.uploadLocal", { local_upload: 1, poster_id: this.poster_id, is_new: this.isNewPosterPlugin ? 1 : 0 });
      let fd = new FormData();
      fd.append("file", this.dataURItoBlob(this.dataURL));
      axios
        .post(uploadImage, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          if (response.data.result == 1) {
            $http
              .post("member.qrcode.poster-record", { poster_id: this.poster_id, image: response.data.data.img_url, is_new: this.isNewPosterPlugin ? 1 : 0 })
              .then(response => {
                if (response.result !== 1) this.$toast(response.msg);
              })
              .catch(error => {
                console.log(error);
              });
          } else {
            this.$toast(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 海报生成 end ===================

    gotoMemberGrade() {
      if (this.member_info.jump_level_page) {
        this.$router.push(this.fun.getUrl("MemberGradeList")); // 跳转至会员权益
      }
    },

    gotoAppRevardVideo(_data) {
      //看广告视频方案：点击入口按钮，跳转到原生APP里看视频广告。
      //传参：会员ID和会员的token
      let _uid = window.localStorage.getItem("uid") || "0"; //会员id
      let _token = _data.member_token || "0"; //会员的token
      if (this.fun.getPhoneEnv() == "1") {
        // 调用IOS方法
        let _iosUid = "uid=" + _uid;
        let _iosToken = "token=" + _token;
        window.webkit.messageHandlers.revardVideo.postMessage(_iosUid, _iosToken);
      } else if (this.fun.getPhoneEnv() == "2") {
        //  调用安卓方法
        revardVideo.revardVideoClick(_uid, _token);
      }
    },
    // 复制邀请码
    onCopy: function(e) {
      this.$toast({
        message: "复制成功",
        duration: 1000
      });
    },
    onError: function(e) {
      this.$toast({
        message: "复制失败",
        duration: 1000
      });
    },
    //获取滚动条当前的位置
    getScrollTop() {
      var scrollTop = 0;
      if (documentElement && documentElement.scrollTop) {
        scrollTop = documentElement.scrollTop;
      } else if (body) {
        scrollTop = body.scrollTop;
      }
      return scrollTop;
    },
    //获取当前可视范围的高度
    getClientHeight() {
      var clientHeight = 0;
      if (body.clientHeight && documentElement.clientHeight) {
        clientHeight = Math.min(body.clientHeight, documentElement.clientHeight);
      } else {
        clientHeight = Math.max(body.clientHeight, documentElement.clientHeight);
      }
      return clientHeight;
    },
    //获取文档完整的高度
    getScrollHeight() {
      return Math.max(body.scrollHeight, documentElement.scrollHeight);
    },
    handleScroll() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      this.btnFlag = scrollTop > 60 ? true : false;
      //滚动事件触发
      if (Number(this.getScrollTop() + this.getClientHeight() + 305) >= this.getScrollHeight()) {
        if (this.isLoadMore) {
          // if (this.templateValue === "03") {
          //   this.getMoreDecorate();
          // } else 
          if (this.templateValue === "01") {
            this.getMorePluginData();
          }
        }
        //此处发起请求
        this.isBottom = true;
      } else {
        this.isBottom = false;
      }
    },
    toAuthorizedLogin() {
      if((this.fun.isWeiXin() && !this.wechat_login_mode)||this.fun.getTyep() == 8||this.fun.getTyep() == 21){
        this.$router.push(this.fun.getUrl("AuthorizedLogin", {}, { yz_redirect: base64_encode(document.location.href) }));
        return;
      }
      if (this.fun.isCPS() && this.fun.isCPSAPPI()) {
        window.firstLogin = 1;
        if (this.fun.isIosOrAndroid() === "ios") {
          callIOS({ body: "callIOS" });
        } else {
          callAndroid();
        }
        setTimeout(() => {
          // 防止聚合APP切换不同公众号没有再次登录
          window.firstLogin = 0;
        }, 3000);
      } else {
        let _locationHref = document.location.href;
        sessionStorage.setItem("yz_redirect", base64_encode(_locationHref));
        this.$router.push(this.fun.getUrl("login", {}, {}));
      }
    },
    toLogin() {
      if(this.isInWechatMp()){
        // 如果是微信小程序webview环境下就跳去登录页面
        this.$router.push(this.fun.getUrl("login", {}, { }));
        return;
      }
      let url = this.fun.getSiteRoot() + this.fun.getRealUrl("member.login.index", { yz_redirect: base64_encode(document.location.href) });
      window.location.href = url;
    }
  },
  filters: {
    setBGImage(data) {
      if (data) {
        return { "background-image": `url(${data})` };
      } else {
        return {};
      }
    }
  },
  components: {
    U_memberasset: () => import("components/new_diy/memberasset.vue"),
    U_membermarket: () => import("components/new_diy/membermarket.vue"),
    U_membermerchant: () => import("components/new_diy/membermerchant.vue"),
    U_memberorder: () => import("components/new_diy/memberorder.vue"),
    U_memberrights: () => import("components/new_diy/memberrights.vue"),
    U_membertool: () => import("components/new_diy/membertool.vue"),
    U_membertop: () => import("components/new_diy/membertop.vue"),
    U_article: () => import("components/new_diy/article.vue"),
    U_backup: () => import("components/new_diy/backup.vue"),
    U_blank: () => import("components/new_diy/blank.vue"),
    U_button: () => import("components/new_diy/button.vue"),
    U_community: () => import("components/new_diy/community.vue"),
    U_coupons: () => import("components/new_diy/coupons.vue"),
    U_cube: () => import("components/new_diy/cube.vue"),
    U_deposit: () => import("components/new_diy/deposit.vue"),
    U_form: () => import("components/new_diy/form.vue"),
    U_goods: () => import("components/new_diy/goods.vue"),
    U_goodsgroup: () => import("components/new_diy/goodsgroup.vue"),
    U_goodsnearby: () => import("components/new_diy/goodsnearby.vue"),
    U_goodsrush: () => import("components/new_diy/goodsrush.vue"),
    U_goodstores: () => import("components/new_diy/goodstores.vue"),
    U_headline: () => import("components/new_diy/headline.vue"),
    U_homedata: () => import("components/new_diy/homedata.vue"),
    U_line: () => import("components/new_diy/line.vue"),
    U_livestreaming: () => import("components/new_diy/livestreaming.vue"),
    U_location: () => import("components/new_diy/location.vue"),
    U_lottery: () => import("components/new_diy/lottery.vue"),
    U_maps: () => import("components/new_diy/maps.vue"),
    U_notice: () => import("components/new_diy/notice.vue"),
    U_richtext: () => import("components/new_diy/richtext.vue"),
    U_search: () => import("components/new_diy/search.vue"),
    U_staff: () => import("components/new_diy/staff.vue"),
    U_shopfor: () => import("components/new_diy/shopfor.vue"),
    U_shortvideo: () => import("components/new_diy/shortvideo.vue"),
    U_signin: () => import("components/new_diy/signin.vue"),
    U_simplegraph: () => import("components/new_diy/simplegraph.vue"),
    U_slideshow: () => import("components/new_diy/slideshow.vue"),
    U_stores: () => import("components/new_diy/stores.vue"),
    U_storesranking: () => import("components/new_diy/storesranking.vue"),
    U_suspendbutton: () => import("components/new_diy/suspendbutton.vue"),
    U_tabcontrol: () => import("components/new_diy/tabcontrol.vue"),
    U_title: () => import("components/new_diy/title.vue"),
    U_video: () => import("components/new_diy/video.vue"),
    U_foot: () => import("components/new_diy/foot.vue"),
    U_ywmgroup: () => import("components/new_diy/ywmgroup.vue"),
    U_moretabcontrol: () => import("components/new_diy/multistageTab.vue"),
    fight_group: () => import("components/member/fight_group.vue"),
    U_bonuspool: () => import("components/new_diy/bonusPoolsShow.vue"),
    U_lawyer: () => import("components/new_diy/lawyer.vue"),
    U_integral : () => import("components/new_diy/integral.vue"),
    U_taskPackage: () => import("components/new_diy/taskPackage.vue"),
    U_membershipLevel: () => import("components/new_diy/membershipLevel.vue"),
    teamName,
    yzGoodsposter,
    DConnectCustomerService,
    U_memberYs: () => import("../../components/new_diy/ys_member.vue"),
    U_calcVal: () => import("@/components/new_diy/calcVal.vue"),
    U_regionExternalReward,
    emptyImage,
    cloud_shop_member,
    guidancePopup,
    cloud_shop_template
  }
};

// 定义底部几个装修组件的默认数据
let recommendGoods = {
  preview_color: "#f5f5f5",
  sort_style: {
    choose_icon: "2"
  },
  padding_top: 0,
  padding_bottom: 0,
  padding_left: 10,
  padding_right: 10,
  item_radius: 5,
  show_shadow: false,
  show_border: false,
  border_color: "#BFB7B7",
  good_tag: {
    choose_icon: "0",
    image: ""
  },
  button_type: "3",
  button_title: "立即购买",
  button_bg_color: "#ff2c29",
  button_color: "#ffffff",
  content_list: ["1", "3", "4", "7"],
  show_price_text: false,
  disable_good: "0",
  goods_type: "list"
};
let limitBuyGoods = {
  preview_color: "#f5f5f5",
  sort_style: {
    choose_icon: "2"
  },
  padding_top: 0,
  padding_bottom: 0,
  padding_left: 10,
  padding_right: 10,
  item_radius: 5,
  show_shadow: false,
  show_border: false,
  border_color: "#BFB7B7",
  good_tag: {
    choose_icon: "0",
    image: ""
  },
  button_type: "3",
  button_title: "立即购买",
  button_bg_color: "#ff2c29",
  button_color: "#ffffff",
  content_list: ["1", "3", "4", "7"],
  show_price_text: false,
  disable_good: "0",
  goods_type: "list"
};
let article = {
  get_style: "1",
  get_number: 999,
  article_style: "2",
  article_bg: "#f5f5f5",
  show_tab: true,
  article_tab_bg: "#ffffff",
  title_color: "#333",
  title_active_color: "#ff2c29"
};
let storeCashier = {
  get_number: 999,
  preview_color: "#f5f5f5",
  font_size: 14,
  font_color: "#666666",
  border_radius: 35,
  class_font_size: 14,
  class_font_color: "#ffffff",
  class_bg_color: "#adadad",
  class_border_radius: 5,
  location_font_size: 14,
  location_font_color: "#666666",
  discount_font_size: 14,
  discount_title_color: "#ff2c29",
  discount_font_color: "#666666",
  discount_list: ["1", "2", "3", "4"],
  tag_font_size: 14,
  tag_font_color: "#666666",
  tag_bg_color: "#f3f2f2",
  tag_border_color: "#ff8400",
  tag_border_radius: 5,
  show_goods: true,
  tab_list: [],
  tab_bg_color: "#ffffff",
  tab_color: "#333333",
  tab_active_color: "#ff8400"
};
let microCommunities = {
  get_style: "1",
  get_number: 999,
  preview_color: "#f5f5f5",
  tab_bg: "#ffffff",
  title_color: "#333",
  title_active_color: "#ff2c29"
};
let videoShare = {
  preview_color: "#f5f5f5",
  get_style: "1",
  get_number: 999
};
let room = {
  choose_tab: "0",
  get_number: 20,
  preview_color: "#f5f5f5",
  record_id: 1,
  tab_active_color: "#ff2c29",
  tab_bg_color: "#ffffff",
  tab_color: "#333333"
};
// 定义底部几个装修组件的默认数据 end ==================